package com.briup.smartcity.aop;

import com.briup.smartcity.bean.BaseLog;
import com.briup.smartcity.exception.ServiceException;
import com.briup.smartcity.mapper.BaseLogMapper;
import com.briup.smartcity.mapper.extend.BaseLogExtendMapper;
import com.briup.smartcity.utils.JwtUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

//切面类
//1、如果实现AOp功能，添加aop依赖信息
@Aspect
@Component
public class logAspect {
    //所有的连接点称为连接点
    //切入点：部分连接点，根据切入规则
    @Pointcut("execution(* com.briup.smartcity.web.controller.*.*(..)) && @annotation(Logging)")   //使用@Pointcut编写哪些方法需要日志
    public void LogCutPoint(){

    }
    @Autowired
    private BaseLogMapper mapper;
    @Autowired
    private BaseLogExtendMapper extendmapper;
    @Before("LogCutPoint()")
    public void before(){   //通知，
        System.out.println("前置信息");
        //获取到浏览器访问系统的请求信息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = sra.getRequest();
        //将请求信息封装到日志对象中
        BaseLog log = new BaseLog();
        //获取请求方式
        log.setLogRequestMethod(request.getMethod());
        //获取请求url
        log.setLogRequestUri(request.getServletPath());
        //获取访问执行时间
        log.setLogTime(new Date());
        String token = request.getHeader("Authorization");

        if(token==null){
            throw new ServiceException("用户未登录");
        }
        String username = JwtUtil.getUserId(token);
        Map<String, Object> map = JwtUtil.getInfo(token);
        log.setLogUsername(username);
        log.setLogRealname((String)map.get("realName"));
        //将日志保存到数据库
        mapper.insertSelective(log);
        if(extendmapper.findAll()>=10){
            extendmapper.deletesome();
        }
    }
    @After("LogCutPoint()")
    public  void after(){
        System.out.println("后置通知");
    }
    @Around("LogCutPoint()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("开始环绕通知");
        Object object = pjp.proceed();
        System.out.println("结束环绕通知");
        return object;
    }
}
